package com.outsider.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

public class OkHttp3 {
	private okhttp3.OkHttpClient httpClient;
	private static OkHttp3 instance = null;

	public static OkHttp3 getInstance() {
		if (instance == null) {
			synchronized (OkHttp3.class) {
				if (instance == null)
					instance = new OkHttp3();
			}
		}
		return instance;
	}

	private OkHttp3() {
		// 分别设置Http的连接,写入,读取的超时时间
		httpClient = new okhttp3.OkHttpClient().newBuilder().connectTimeout(10, TimeUnit.SECONDS)
				.writeTimeout(10, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();
	}

	private static final okhttp3.MediaType CONTENT_TYPE_FORM = okhttp3.MediaType
			.parse("application/x-www-form-urlencoded");

	private String exec(okhttp3.Request request) {
		try {
			okhttp3.Response response = httpClient.newCall(request).execute();

			if (!response.isSuccessful())
				throw new RuntimeException("Unexpected code " + response);

			return response.body().string();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public String get(String url) {
		okhttp3.Request request = new okhttp3.Request.Builder().url(url).get().build();
		return exec(request);
	}

	// public String get(String url,String authorization){
	// okhttp3.Request request = new
	// okhttp3.Request.Builder().addHeader("Authorization",
	// authorization).url(url).get().build();
	// return exec(request);
	// }

	public String getWithHeader(String url, Map<String, String> header) {
		okhttp3.Request.Builder builder = new okhttp3.Request.Builder();
		for (Entry<String, String> entry : header.entrySet()) {
			builder.addHeader(entry.getKey(), entry.getValue());
		}
		okhttp3.Request request = builder.url(url).get().build();
		return exec(request);
	}

	public String get(String url, Map<String, String> queryParas) {
		okhttp3.HttpUrl.Builder urlBuilder = okhttp3.HttpUrl.parse(url).newBuilder();
		for (Entry<String, String> entry : queryParas.entrySet()) {
			urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
		}
		okhttp3.HttpUrl httpUrl = urlBuilder.build();
		okhttp3.Request request = new okhttp3.Request.Builder().url(httpUrl).get().build();
		return exec(request);
	}

	public String post(String url, String params) {
		okhttp3.RequestBody body = okhttp3.RequestBody.create(CONTENT_TYPE_FORM, params);
		okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(body).build();
		return exec(request);
	}

	public String post(String url, Map<String, String> header, Map<String, String> params) {
		okhttp3.Request.Builder builder = new okhttp3.Request.Builder();
		for (Entry<String, String> entry : header.entrySet()) {
			builder.addHeader(entry.getKey(), entry.getValue());
		}
		okhttp3.FormBody.Builder rb = new FormBody.Builder();

		for (Entry<String, String> entry : params.entrySet()) {
			rb.add(entry.getKey(), entry.getValue());
		}
		okhttp3.Request request = builder.url(url).post(rb.build()).build();
		return exec(request);
	}

	//限制单线程 歌单下载系列Bug
	public synchronized boolean download(String url, String path, String name) {
		long start = System.currentTimeMillis();
		okhttp3.Request request = new okhttp3.Request.Builder().url(url).get().build();
		InputStream is=null;
		byte[] buf=new byte[2048];
		FileOutputStream fos=null;
		File file=null;
		okhttp3.Response response=null;
		try {
			response = httpClient.newCall(request).execute();
			if (!response.isSuccessful())
				throw new RuntimeException("Unexpected code " + response);

			okhttp3.ResponseBody body = response.body();
			File saveDir = new File(path);
			if (!saveDir.exists()) {
				saveDir.mkdirs();
			}
			file = new File(path + File.separator + name);
			fos=new FileOutputStream(file);
			is=body.byteStream();
			int len=0;
			while((len=is.read(buf))!=-1){
				fos.write(buf, 0, len);			
			}
			fos.flush();
			System.out.println(System.currentTimeMillis()-start);
			return true;

		} catch (IOException e) {
			e.printStackTrace();
			return false;
			
		} finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }
        	if (response!=null&&response.body()!=null)
        		response.body().close();


        }

	}

}